﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Sofire.DataComm.Remoting.Client
{
    /// <summary>
    /// 表示契约的一个本地方法。
    /// </summary>
    public class MethodImpl
    {
        /// <summary>
        /// 契约标识索引。
        /// </summary>
        public readonly int Ident;
        /// <summary>
        /// 契约的方法。
        /// </summary>
        public readonly MethodInfo MethodInfo;
        /// <summary>
        /// 契约的方法名称。
        /// </summary>
        public readonly string Name;

        internal MethodImpl(int ident, MethodInfo methodInfo)
        {
            this.Ident = ident;
            this.MethodInfo = methodInfo;
            this.Name = methodInfo.Name;
        }

        private int _syncMethodIdent = -1;

        internal int GetMethodIndex(List<MethodSyncInfo> syncMethods)
        {
            if(this._syncMethodIdent == -1)
            {
                var methodParams = this.MethodInfo.GetParameters();

                var ident = -1;
                // 筛选与远程服务器上曝露的接口比较。
                foreach(var si in syncMethods)
                {
                    if(si.MethodName == this.Name
                        && methodParams.Length == si.ParameterTypes.Length)
                    {
                        var matchingParameterTypes = true;
                        for(int i = 0 ; i < methodParams.Length ; i++)
                        {
                            if(!methodParams[i].ParameterType.FullName.Equals(si.ParameterTypes[i].FullName))
                            {
                                matchingParameterTypes = false;
                                break;
                            }
                        }
                        if(matchingParameterTypes)
                        {
                            ident = si.MethodIdent;
                            break;
                        }
                    }

                }
                this._syncMethodIdent = ident;
            }
            return this._syncMethodIdent;
        }
    }
}
